package xyz.xtt.exchange.service.impl;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;

import xyz.xtt.common.starter.cache.CacheManager;
import xyz.xtt.exchange.constants.ExchangeCache;
import xyz.xtt.exchange.entity.TblArtAmberCard;
import xyz.xtt.exchange.mapper.TblArtAmberCardMapper;
import xyz.xtt.exchange.response.ArtAmberCardResponse;
import xyz.xtt.exchange.service.ITblArtAmberCardService;

/**
 * <p>
 * 卡片明细表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-19
 */
@Service
public class TblArtAmberCardServiceImpl extends ServiceImpl<TblArtAmberCardMapper, TblArtAmberCard> implements ITblArtAmberCardService {
	@Autowired
	private CacheManager cacheManager;

	private List<ArtAmberCardResponse> typeCards(List<TblArtAmberCard> queryList) {
		Map<String, Long> groupCount = queryList.stream().collect(groupingBy(TblArtAmberCard::getRarityType, Collectors.counting()));
		Map<String, TblArtAmberCard> toMap = queryList.stream().collect(toMap(TblArtAmberCard::getRarityType, Function.identity(), (a, b) -> a));
		List<ArtAmberCardResponse> resultList = Lists.newArrayList();
		toMap.forEach((k, v) -> {
			ArtAmberCardResponse build = ArtAmberCardResponse
					.builder()
					.amount(groupCount.get(k))
					.imgUrl(v.getProfileImg())
					.rarityType(v.getRarityType())
					.amberOrderId(v.getAmberOrderId())
					.build();
			resultList.add(build);
		});
		return resultList.stream().sorted(Comparator.comparing(ArtAmberCardResponse::getRarityType).reversed()).collect(toList());
	}

	@Override
	public List<ArtAmberCardResponse> queryCards(Long appUid, Long orderId) {
		List<TblArtAmberCard> userCardList = queryArtAmberCardWithUid(appUid);
		if (Objects.nonNull(orderId)) {
			List<TblArtAmberCard> list = userCardList.stream().filter(x -> Objects.equals(orderId, x.getAmberOrderId())).collect(toList());
			return typeCards(list);
		}
		return typeCards(userCardList);
	}

	@Override
	public List<TblArtAmberCard> queryArtAmberCardWithUid(Long appUid) {
		List<TblArtAmberCard> cacheList = cacheManager
				.cacheList(() -> queryArtAmberCardInfo(appUid), ExchangeCache.QUERY_ART_CARD_WITH_UID, String.valueOf(appUid));
		return cacheList;
	}

	@Override
	public List<TblArtAmberCard> queryArtAmberCardInfo(Long appUid) {
		List<TblArtAmberCard> list = new LambdaQueryChainWrapper<>(baseMapper).eq(TblArtAmberCard::getAppUserId, appUid).list();
		return list;
	}

}
